#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <sys/epoll.h>
#include "../source/public.h"

framework::Logger::ptr g_logger = FRAMEWORK_LOG_ROOT();

void test_fiber()
{
    FRAMEWORK_LOG_DEBUG(g_logger) << "test fiber ==========";

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    fcntl(sock, F_SETFL, O_NONBLOCK); //O_NONBLOCK 设置I/O为非阻塞模式

    sockaddr_in addr;
    memset(&addr, 0, sizeof(sockaddr_in));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr.s_addr);

    if(!connect(sock, (const sockaddr*)&addr, sizeof(addr)))
    {
        std::cout << "connect error" << std::endl;
    }
    else if(errno == EINPROGRESS)
    {
        /*EINPROGRESS 错误只是指示操作仍在进行中，并不表示出现了错误。
        它通常在非阻塞操作中使用，以允许程序继续执行其他任务而不会阻塞在操作完成之前。*/
        framework::IOManager::GetThis()->addEvent(sock, framework::IOManager::READ, [](){
            FRAMEWORK_LOG_INFO(g_logger) << "read callback";
        });
        framework::IOManager::GetThis()->addEvent(sock, framework::IOManager::WRITE, [sock](){
            FRAMEWORK_LOG_INFO(g_logger) << "write callback";
            //close(sock);
            framework::IOManager::GetThis()->cancelEvent(sock, framework::IOManager::READ);
            close(sock);
        });
    }
    else
    {
        std::cout <<  errno << " " << strerror(errno) << std::endl;
    }

    FRAMEWORK_LOG_INFO(g_logger) << "test fiber finish";
}

void test1()
{
    std::cout << "EPOLLIN=" << EPOLLIN
              << " EPOLLOUT=" << EPOLLOUT << std::endl;
    framework::IOManager iom(2, false);
    iom.schedule(&test_fiber);
}

framework::Timer::ptr t;
void test_timer()
{
    framework::IOManager io(2);
    
    t = io.addTimer(1000, [](){

        static int i = 0;
        FRAMEWORK_LOG_INFO(g_logger) << "hello timer i = " << i;
        if(++i == 3)
        {
            t->reset(2000, true);
        }
        if(i == 6)
        {
            t->cancel();
        }

    },true);

}

int main(void)
{
    // test1();
    test_timer();

    return 0;
}

